package com.zxd.interview.jmm;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 不适用volatile的场景
 */
public class NoVolatile implements Runnable{

    volatile int a;

    AtomicInteger realA = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        NoVolatile noVolatile = new NoVolatile();
        Thread thread1 = new Thread(noVolatile);
        thread1.start();
        Thread thread2 = new Thread(noVolatile);
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("noVolatile.a => "+ noVolatile.a);
        System.out.println("AtomicInteger.realA => "+ noVolatile.realA.get());


    }/**
     volatile 不适用的场景：非原子操作

     noVolatile.a => 1988
     AtomicInteger.realA => 2000
     */


    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            a++;
            realA.incrementAndGet();
        }
    }
}
